<template>
  <z-modal
    v-bind="modalOption"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model layout="horizontal" labelAlign="right" ref="ruleForm" :label-col="labelCol" :wrapper-col="wrapperCol" :model="form" :rules="validatorRules">
        <a-row>
          <a-col :span="8" >
            <a-form-model-item label="编码" prop="code">
              <a-input placeholder="请输入编码" :disabled="disableSubmit || editType !== 'add'" v-model.trim="form.code"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="名称" prop="name">
              <a-input placeholder="请输入名称" :disabled="disableSubmit" v-model.trim="form.name"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="数字框">
              <a-input-number class="!w-full" :disabled="disableSubmit" placeholder="请输入数字框" v-model="form.number"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="日期框">
              <a-date-picker class="!w-full" :disabled="disableSubmit" placeholder="请选择日期" v-model="form.date1"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="日期框(时分秒)">
              <a-date-picker class="!w-full" show-time :disabled="disableSubmit" placeholder="请选择日期" v-model="form.date2"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="字典(下拉)">
              <ZDictSelectTag :disabled="disableSubmit" :defaultValue="true" v-model="form.dict1" dictCode="MB_SYSTEM_YES_NO" />
              <!-- defaultValue 根据字典配置的默认值设置表单初始值 -->
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="字典(单选组件)">
              <ZDictSelectTag :disabled="disableSubmit" type="radio"  v-model="form.dict2" dictCode="MB_SYSTEM_YES_NO" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="文件上传">
              <z-upload v-model="form.fileList" ></z-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item  label="文本框">
              <a-input :disabled="disableSubmit" type="textarea" v-model="form.memo"/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <a-tabs v-model="activeKey">
        <a-tab-pane tab="表单" :key="refKeys[0]" forceRender>
          <a-form-model layout="horizontal" labelAlign="right" :ref="refKeys[0]" :label-col="labelCol" :wrapper-col="wrapperCol" :model="subForm" :rules="subFormRules">
            <a-row>
              <a-col :span="8" >
                <a-form-model-item label="子表字段1" prop="filed1">
                  <a-input placeholder="请输入子表字段1" :disabled="disableSubmit" v-model.trim="form.filed1"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" >
                <a-form-model-item label="子表字段2" prop="filed2">
                  <a-input placeholder="请输入子表字段2" :disabled="disableSubmit" v-model.trim="form.filed2"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-tab-pane>
        <a-tab-pane tab="明细" :key="refKeys[1]" forceRender>
          <vxe-grid
            :ref="refKeys[1]"
            :columns="detailTable.column"
            :data="detailTable.dataSource"
            :edit-rules="detailTable.validRules"
            v-bind="vxeTableOption"
          >
          </vxe-grid>
        </a-tab-pane>
      </a-tabs>
    </a-spin>
  </z-modal>
</template>

<script>
import ModalFormMixin from '@/mixins/ModalFormMixin'
import { CURY_TYPE } from '@/store/mutation-types'
import { duplicateCheck } from '@/services/common'
import debounce from 'lodash/debounce'
import moment from 'moment'
import { getAction } from '@/services/manage'
import ZDictSelectTag from '@/components/dict/ZDictSelectTag'
import ZUpload from '@/components/zz/ZUpload'
import { minValid, maxValid } from '@/utils/vxe-table-util'
export default {
  name: 'Auto2Modal',
  mixins: [ModalFormMixin],
  components: {
    ZDictSelectTag,
    ZUpload
  },
  data() {
    return {
      validatorRules: { // 定义主单校验
        name: [{ required: true, message: '请输入名称!' }],
        code: [
          { required: true, message: '请输入编码!' },
          { validator: (rule, value, callback) => this.validateDuplicate(rule, value, callback), trigger: 'change' }
        ]
      },
      url: {
        add: '/sys/dict/add',
        edit: '/sys/dict/edit'
      },
      fileNames: [],
      refKeys: ['item1', 'item2'],
      activeKey: 'item1',
      detailTable: { // 明细
        column: [ // 明细列
          { type: 'checkbox', width: 40 },
          { type: 'seq', width: 40 },
          { title: '行号', field: 'lineNo', width: 60 },
          { title: '编码', field: 'code', editRender: { name: 'AInput' }},
          { title: '名称', field: 'name', width: 100 },
          { title: '单位', field: 'unit', cellRender: { name: 'ZDictCell', props: { dictCode: 'ERP_TECH_UNIT_CODE' }}},
          { title: '数量', field: 'quantity', editRender: { name: 'AInput', props: { type: 'number' }}},
          { title: '字典', field: 'checkResult', editRender: { name: 'ZDictSelectTag', props: { dictCode: 'MB_QUALITY_CHECK_RESULT' }}},
          { title: '时间', field: 'qualityDate', editRender: { name: 'ADatePicker', props: { 'valueFormat': 'YYYY-MM-DD' }}}
        ],
        dataSource: [], // 明细数据
        validRules: { // 明细校验
          quantity: [
            { required: true, message: '请输入数量' },
            { validator: (data) => minValid({ ...data, min: 0 }) }, // 校验大于min
            { validator: (data) => maxValid({ ...data, max: data.row.quantity, equal: true }) } // 校验 小于等于max
          ],
          code: [
            { required: true, message: '请输入编码' }
          ]
        }
      },
      subForm: {}, // 子表数据
      subFormRules: { // 子表校验
        filed1: [{ required: true, message: '请输入字段1' }],
        filed2: [{ required: true, message: '请输入字段2' }]
      }
    }
  },
  methods: {
    addAfter() {
      // 新增设置默认值
      this.$set(this.form, 'date1', moment().format('YYYY-MM-DD'))
    },
    editAfter() {
      this.confirmLoading = true

      // 根据主单编码请求子表数据
      getAction(this.url.list + this.model.code).then(res => {
        if (res.success) {
          this.subForm = res.result
        }
      })

      // 根据主单编码请求明细数据
      this.requestSubTableData(this.url.list + this.model.code, {}, this.detailTable, (res) => {
        this.confirmLoading = false
        // 防止后台请求数据字段少时。前台输入框无法输入
        this.createdVxeTableData(this.refKeys[1], this.detailTable.dataSource)
      })
    },
    classifyIntoFormData() {
      // 设置主单脏数据状态
      this.form.crudType = this.editType === 'add' ? CURY_TYPE.SAVE : CURY_TYPE.UPDATE
      // 设置子表脏数据状态
      this.subForm.crudType = this.editType === 'add' ? CURY_TYPE.SAVE : CURY_TYPE.UPDATE

      const data = this.$refs[this.refKeys[1]].getRecordset()
      // 设置明细脏数据状态
      const tableData = this.setDataCrud(data)
      return { // 整理数据结构为后台需要的格式
        ...this.form,
        subForm: this.subForm,
        detailsLines: tableData
      }
    },
    validateDuplicate: debounce(function(rule, value, callback) { // 唯一校验
      if (!value) {
        callback()
      } else {
        duplicateCheck({
          tableName: 'mb_erp_inventory_item',
          column: 'item_code_',
          key: value,
          exclude: this.editType === 'edit' ? value : undefined
        }).then(res => {
          if (res.success) {
            res.result === 0 ? callback() : callback('编码已存在')
          } else {
            this.$message.warning(res.message)
          }
        })
      }
    }, 400)
  }
}
</script>
